<?php
/**
 * Handles user login, logout, and registration functions for the site.
 * Will include activation, forgot password, and other user management functions
 * in the future.
 *
 * ACCESS: PUBLIC
 *
 * @author Chris Lunsford
 * @version 1.0
 */
class Site extends Controller {
	
	/**
	 * Class constructor
	 */
	function __construct() {
		parent::__construct();
		
		$this->load->library('BadgerController');	
	}
	
	function index() {
		redirect('xa');
	}
	
	/**
	 * Placeholder for catcing redirects from successful logins
	 * Should be deprecated and replaced with proper redirects.
	 */
	function success() {
		redirect('blog');
	}
	
	/**
	 * Placeholder for catching failed access checks to admin areas
	 * Should be replaced with flash message and proper redirect
	 */
	function deadend() {
		$this->load->view('deadend');
	}
	
	/**
	 * Attempts a login for the current user, if the login is unsuccessful the login form is displayed.
	 */	
	function login() {
		$this->badgercontroller->login();
		$data = $this->_buildContent();
		$data['input_username'] = array('name' => 'username', 'size' => '20');
		$data['input_password'] = array('name' => 'password', 'size' => '20');
		$this->load->view('site/login', $data);
	}
	
	/**
	 * Logs out the current user.
	 */
	function logout() {
		$this->badgercontroller->logout();
		redirect('');
	}
	
	/**
	 * Submits a registration form for the current user, if the
	 * registration is unsuccessful, the registration form is displayed.
	
	function register() {
		redirect('');
		//$this->badgercontroller->register();
		//$this->load->view('register');
	}
	
	/**
	 * Loads signup page for XAcms beta
	 
	function signup() {
		$this->load->view('signup');
	}
	*/
	
	/**
	 * Sends an email with the username to the email address on file
	 */
	function forgotUsername() {
		$this->load->library('validation');
		
		$rules['email'] = "trim|required|valid_email|callback_isEmail";
		$this->validation->set_rules($rules);
		
		$fields['email']	= 'Email Address';
		$this->validation->set_fields($fields);
	
		$this->validation->set_error_delimiters('<div class="error">','</div>');
		
		if($this->validation->run() == FALSE) {
			$data = $this->_buildContent();
			$this->load->view('site/forgotUsername', $data);
		} else {
			$email = $this->input->post('email',TRUE);
			$user = $this->UserModel->getUserByEmail($email);
			$this->session->set_flashdata('msg_info', 'Your username was mailed to the email address you provided.');
						
			//and send the user an email :)
			$this->load->library('email');
			$this->email->from('donotreply@xa-ncsu.com','Chi Alpha Christian Fellowship');
			$this->email->to($email);
			$this->email->subject('XA-NCSU.COM - Username Reminder');
			$this->email->message("You requested to have your username sent to you in a reminder email.  Your username is:\n\n".$user->username.".\n\nThanks,\n\nChi Alpha Christian Fellowship");
			$this->email->send();
			
			redirect('site/login');
		}
	}
	
	/*
	 * Callback function to make sure the email supplied is in the database
	 * @param str the email address being supplied
	 * @return whether the username is unique to the database (TRUE/FALSE)
	 */
	function isEmail($str) {
		if ($this->UserModel->getUserByEmail($str) == FALSE) {
			$this->validation->set_message('isEmail', 'This email address does not match any of our records.  Please supply a different email address or create a new account.');
			return FALSE;
		} else {
			return TRUE;
		}
	}
	
	/**
	 * Creates a new random password for the user and emails to address on file
	 */
	function forgotPassword() {
		//they're going to supply us a username and we're going to create a random password for them
		$this->load->library('validation');
		
		$rules['username'] = "trim|required|xss_clean|callback_isUsername";
		$this->validation->set_rules($rules);
		
		$fields['username']	= 'Username';
		$this->validation->set_fields($fields);
	
		$this->validation->set_error_delimiters('<div class="error">','</div>');
		
		if($this->validation->run() == FALSE) {
			$data = $this->_buildContent();
			$this->load->view('site/forgotPassword', $data);
		} else {
			$username = $this->input->post('username',TRUE);
			$user = $this->UserModel->getUserByName($username);
			$post['userid'] = $user->userid;
			$post['token'] = $token = sha1($user->username.time());
			$post['created'] = time() + 3600;
			$this->UserModel->deleteOldTokens($user->userid); //delete all old tokens first, only one can be active at a time
			$this->UserModel->createToken($post);

			$this->session->set_flashdata('msg_info', 'An email with a confirmation token was sent to your email address.  Visit the url in the email to have your password reset.');
						
			//and send the user an email :)
			$this->load->library('email');
			$this->email->from('donotreply@xa-ncsu.com','Chi Alpha Christian Fellowship');
			$this->email->to($user->email);
			$this->email->subject('XA-NCSU.COM - Password Reset');
			$this->email->message("A request was made to reset the password for this account.  If you did not make this request, ignore this email.  If you would like to have your password reset, visit the following link:\n\n".site_url()."site/confirmToken/".$token."/.\n\nOnce you do, a new password will be emailed to you.  Thanks,\n\nChi Alpha Christian Fellowship");
			$this->email->send();
			
			redirect('site/login');
		}
	}
	
	/**
	 *
	 */
	function confirmToken() {
		$token = $this->uri->segment(3);
		if ($token != '' && $this->UserModel->checkToken($token)) {
			//if the token matches...then:
			$this->load->helper('string');
			$newPassword = random_string('alnum', 8);
			$userid = $this->UserModel->getToken($token)->userid;
			//need to do a password update in the database
			if ($userid != '') {
				$user = $this->UserModel->getUser($userid);
				$this->UserModel->updatePassword($userid,$newPassword);
				$this->UserModel->deleteToken($token);
				$this->session->set_flashdata('msg_info', 'A new password was mailed to the email address associated with your account.  Once you receive the email, please login and change your password');
						
				//and send the user an email :)
				$this->load->library('email');
				$this->email->from('donotreply@xa-ncsu.com','Chi Alpha Christian Fellowship');
				$this->email->to($user->email);
				$this->email->subject('XA-NCSU.COM - Password Reset');
				$this->email->message("You requested to have your password reset.  Your new password is:\n\n".$newPassword."\n\nYou can now login and change your password on your profile page.  Thanks,\n\nChi Alpha Christian Fellowship");
				$this->email->send();
			} else {
				$this->session->set_flashdata('msg_error', 'Your attempt to reset your password failed.');
			}
			redirect('site/login');
		} else {
			$this->session->set_flashdata('msg_error', 'Your attempt to reset your password failed.');
			redirect('site/login');
		}
	}
	/*
	 * Callback function to make sure the username supplied is in the database
	 * @param str the username being supplied
	 * @return whether the username is unique to the database (TRUE/FALSE)
	 */
	function isUsername($str) {
		if ($this->UserModel->isUsername($str) == FALSE) {
			$this->validation->set_message('isUsername', 'This username does not match any of our records.  Please supply a different username or create a new account.');
			return FALSE;
		} else {
			return TRUE;
		}
	}
	
	/*
	 * Supplies user-specific information to the interface for customization
	 * REQUIRED DATA ARRAY PARAMS:
	 * pagetype = page, page-admin, nobg
	 * loggedin = isset
	 */
	function _buildContent() {
		$data = array();
		if ($this->session->flashdata('msg_info')) $data['msg_info'] = $this->session->flashdata('msg_info');		
		if ($this->session->flashdata('msg_error'))	$data['msg_error'] = $this->session->flashdata('msg_error');
			
		return $data;
	}
}
?>